const fs = require('fs').promises;
const path = require('path');
const { Base64 } = require('js-base64');

class HarImageExtractor {
  constructor(config) {
    this.harFilePath = config.harFilePath;
    this.outputJsonPath = config.outputJsonPath;
    this.imagesOutputDir = config.imagesOutputDir;
  }

  async extractImages(mainWindow) {
    try {
      // 确保输出目录存在
      await fs.mkdir(this.imagesOutputDir, { recursive: true });
      
      // 读取 .har 文件内容
      let harContent = await fs.readFile(this.harFilePath, 'utf8');
      let harData = JSON.parse(harContent);
      
      // 初始化结果对象
      let result = {};
      
      // 获取所有匹配的图片条目
      const imageEntries = harData.log.entries.filter(entry => {
        const mimeType = entry.response.content.mimeType;
        return mimeType === 'image/webp' || mimeType === 'application/octet-stream' || mimeType === 'image/jpeg';
      });
      
      const totalImages = imageEntries.length;
      
      // 遍历 entries 并查找 mimeType 为 "image/webp" 的条目
      let currentIndex = 1;
      for (let entry of imageEntries) {
        // 更新进度
        if (mainWindow && !mainWindow.isDestroyed()) {
          const progress = Math.round((currentIndex / totalImages) * 100);
          mainWindow.webContents.send('progress-update', { type: 'parse-har', progress });
        }
        
        // 如果 content.text 是 base64 编码的数据，则直接使用
        let base64Data = entry.response.content.text;
        let isBase64Encoded = entry.response.content.encoding === 'base64';
        if (!isBase64Encoded) {
          // 否则，假设它是文本编码（例如 utf-8），需要先转换为 Uint8Array 再进行 base64 编码
          base64Data = Base64.fromUint8Array(new TextEncoder().encode(base64Data));
          isBase64Encoded = true;
        }
        
        let base64Prefix = 'data:image/webp;base64,';
        let fullBase64String = base64Prefix + base64Data;
        
        // 使用请求 URL 或其他唯一标识符作为键
        let key = entry.request.url;
        result[key] = fullBase64String;
        
        // 解码 Base64 数据并保存为图片文件
        let imageFileName = `${currentIndex}.webp`;
        let imagePath = path.join(this.imagesOutputDir, imageFileName);
        let imageBuffer = Buffer.from(base64Data, 'base64');
        await fs.writeFile(imagePath, imageBuffer);
        
        currentIndex++;
      }
      
      // 将结果保存为 JSON 文件
      await fs.writeFile(this.outputJsonPath, JSON.stringify(result, null, 2), 'utf8');
      
      return {
        success: true,
        message: `成功提取 ${totalImages} 张图片`
      };
    } catch (error) {
      console.error('解析HAR文件时发生错误:', error.message);
      throw error;
    }
  }
}

module.exports = HarImageExtractor;